package com.cpi.cornpp.purchaseorder.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.purchase.program.exception.PurchaseProgramException;
import com.cpi.cornpp.purchaseorder.form.PurchaseOrderVersionForm;
import com.cpi.cornpp.purchaseorder.service.PurchaseOrderVersionService;
import com.cs.common.utils.NumberUtil;

public class DeletePurchaseOrderVersionAction extends Action {
	private final static String CUSTOM_EXCEPTION = "custom_exception";//$NON-NLS-1$
	private static final String SUCCESS_FORWARD = "toSuccess";
	private static final String VERSION_ID = "versionId";
	private final static String ERROR_MESSAGE = "ERROR_MESSAGE";//$NON-NLS-1$
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws PurchaseProgramException{
		PurchaseOrderVersionForm povForm = null;
		PurchaseOrderVersionService povService = null;
		HttpSession session = null;
		ActionForward forward = null;
		forward = mapping.findForward(SUCCESS_FORWARD);
		session = request.getSession(false);
		int versionId = 0;
		int purchaseOrderVersionId = 0;
		String messageError = null;
		MessageResources messageResources = null;
		try{
			messageResources = getResources(request);
			povService = new PurchaseOrderVersionService(); 
			povForm = (PurchaseOrderVersionForm) form;
			versionId = NumberUtil.getInt(session.getAttribute(VERSION_ID));
			purchaseOrderVersionId = NumberUtil.parseInt(povForm.getPurchaseOrderVersionId());
			povService.deletePurchaseOrderVersion(versionId, purchaseOrderVersionId);
		} catch(PurchaseProgramException ppe){
			messageError = messageResources.getMessage((Locale)session.getAttribute(Globals.LOCALE_KEY), ppe.getErrorCode());
			if(null == messageError){
				session.setAttribute(CUSTOM_EXCEPTION, ppe);
				form.reset(mapping, request);
				throw ppe;
			}else{
				session.setAttribute(ERROR_MESSAGE, messageError);
			}
		} catch(Exception e){
			PurchaseProgramException ppe=null;
			e.printStackTrace(System.out);
			ppe= new PurchaseProgramException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
			session.setAttribute(CUSTOM_EXCEPTION, ppe);
			throw ppe;
		}
		return forward;
	}
}